from ..base import PermissionRuleHandler, register_handler

@register_handler("field_not_in_list")
class FieldNotInListHandler(PermissionRuleHandler):
    """
    字段列表不匹配处理器 (NOT IN)
    - user_list_field: 用户信息中的列表字段名, 如 'dept_codes'
    - target_field: 数据库表中的字段名, 如 'dept_code'
    - 生成SQL: table.target_field NOT IN ('value1', 'value2')
    """
    def get_required_config_keys(self):
        return ["user_list_field", "target_field"]

    def validate_config(self, config):
        return all(k in config for k in self.get_required_config_keys())

    def generate_sql(self, table_alias: str, config: dict, user: dict) -> str:
        ids = user.get(config["user_list_field"], [])
        
        # 如果用户的值列表为空，NOT IN 条件不适用，应视为通过 (返回 1=1)
        if not ids:
            return "1=1"
            
        # 正确处理字符串值的引用
        quoted_ids = []
        for x in ids:
            if isinstance(x, str):
                # 对字符串中的单引号进行转义
                escaped_x = x.replace("'", "''")
                quoted_ids.append(f"'{escaped_x}'")
            else:
                quoted_ids.append(str(x))
                
        ids_str = ",".join(quoted_ids)
        
        return f"{table_alias}.{config['target_field']} NOT IN ({ids_str})"